package tools

import (
	"bytes"
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"github.com/golang-jwt/jwt/v4"
	"io/ioutil"
	"log"
	"net/http"
)

type Claims struct {
	Apikey string `json:"apikey"`
	jwt.StandardClaims
}

func MD5(str string) string {
	// 创建一个MD5哈希对象
	hash := md5.New()
	// 写入要加密的数据
	hash.Write([]byte(str))
	// 计算MD5哈希值
	sum := hash.Sum(nil)
	// 将哈希值转换为十六进制字符串
	md5String := hex.EncodeToString(sum)
	return md5String
}

func GenerateToken(apiKey string) (string, error) {
	claims := &Claims{
		Apikey: apiKey,
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := token.SignedString([]byte("my_secret_key"))
	return tokenString, err
}

func ParseToken(tokenString string) (string, error) {
	claims := &Claims{}
	token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
		return []byte("my_secret_key"), nil
	})
	if err != nil || !token.Valid {
		return "", err
	}
	return claims.Apikey, nil
}

func SendGet(url string) ([]byte, error) {
	// 将data转换为json字节数组
	jsonData, err := json.Marshal(nil)
	if err != nil {
		log.Println("jsonData error:", err)
		return nil, err
	}

	// 创建http请求
	req, err := http.NewRequest("GET", url, bytes.NewBuffer(jsonData))
	if err != nil {
		log.Println("NewRequest error:", err)
		return nil, err
	}

	// 发送请求
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Println("Do error:", err)
		return nil, err
	}
	defer resp.Body.Close()

	// 读取响应内容
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Println("body error:", err)
		return nil, err
	}

	return body, nil
}
